package org.mspring.mlog.api.spider.service;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.mspring.mlog.api.spider.dao.SpiderPostDao;
import org.mspring.mlog.api.spider.entity.SpiderPost;
import org.mspring.mlog.entity.Catalog;
import org.mspring.mlog.entity.Post;
import org.mspring.mlog.service.PostService;
import org.mspring.platform.dao.Page;
import org.mspring.platform.dao.query.QueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Gao Youbo
 * @since 2013-5-3
 */
@Service
@Transactional
public class SpiderPostService {

    @Autowired
    private PostService postService;
    @Autowired
    private SpiderPostDao spiderPostDao;

    public void createSpiderPost(SpiderPost spiderPost) {
        spiderPost.setCreateTime(new Date());
        spiderPost.setPosted(false);
        spiderPostDao.insert(spiderPost);
    }

    public void changePosted(boolean posted, Long... ids) {
        if (ids == null || ids.length == 0) {
            return;
        }
        for (long id : ids) {
            spiderPostDao.changePosted(id, posted);
        }
    }

    public void publishPost(Long[] catalogs, Long... id) {
        if (id == null) {
            return;
        }
        SpiderPost sp = null;
        Post post = null;
        for (Long i : id) {
            sp = spiderPostDao.get(i);
            if (sp == null) {
                continue;
            }
            post = new Post();
            post.setTitle(sp.getTitle());
            post.setContent(sp.getContent());
            if (catalogs != null && catalogs.length > 0) {
                Set<Catalog> cset = new HashSet<>();
                for (Long catalog : catalogs) {
                    cset.add(new Catalog(catalog));
                }
                post.setCatalogs(cset);
            }
            postService.create(post);
            changePosted(true, i);
        }
    }

    public Page<SpiderPost> listPage(QueryBuilder queryBuilder, Page<SpiderPost> page) {
        return spiderPostDao.listPage(queryBuilder, page);
    }

    public SpiderPost findById(long id) {
        return spiderPostDao.get(id);
    }

    public void delete(Long... id) {
        spiderPostDao.delete(id);
    }

    public void update(SpiderPost spiderPost) {
        spiderPostDao.update(spiderPost);
    }

}
